﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;

using UnityEventUtils;
using CoverShooter;

namespace Manager {
	// 管理游戏中的所有坦克,  包括自己的和 网络上其它玩家的
	public class RolesManager : MonoBehaviour    
	{
		#region  -------------------------初始化
		[HideInInspector] public OtherThirdPersonInput[] m_OtherRoles;
		[HideInInspector] public SelfThirdPersonInput m_SelfRole;
		public GameObject m_Prefab;
        public GameObject m_OtherPrefab;
        public ThirdPersonCamera m_ThirdPersonCamera;

        public GameObject[] SpawnPoint;

        public Text m_SelfMessage;
		private bool m_isInited = false;
		private int m_RoleCount = 10;
        private int[,] m_positionArray = new int[4, 2] {{125, -120}, {125, 25}, {30, -120}, {30, 27}};
        public List<Color> m_ColorList;
		#endregion

		#region  -------------------------网络
        [HideInInspector] public UEvent_s m_OverEvent = new UEvent_s();
        [HideInInspector] public UnityEvent m_RelifeEvent = new UnityEvent();
		private NetworkingManager m_NetworkingManager;
        #endregion

        #region  -------------------------冷却
        public Image m_CoolingImage;
		private bool m_isCooling = false;
		private float m_CoolTime = 5.0f;
		private float m_Timer = 0;
		private WaitForSeconds m_ReliveWait = new WaitForSeconds (10f);
        #endregion

        #region  -------------------------测试
        //public FollowControl m_followControl;
        //[SerializeField] WorldMessageControl _worldMessageControl;
		#endregion

		void Start ()
		{
            m_NetworkingManager = NetworkingManager.getInstance();
            if (m_NetworkingManager != null){
				m_NetworkingManager.m_NotifyEvent.AddListener(SynOtherRoleMove);
				m_NetworkingManager.m_CreateEvent.AddListener(createOtherRoles);
				m_NetworkingManager.m_ShootEvent.AddListener(SynOtherShoot);
				m_NetworkingManager.m_HealthEvent.AddListener(SynOtherHealth);
				m_NetworkingManager.m_AllDataEvent.AddListener(SynAllSynDataOfSelfRole);
				m_NetworkingManager.m_DeathEvent.AddListener(SynOtherDeath);
				m_NetworkingManager.m_LockedTargetEvent.AddListener(SynOtherLockedTarget); 
                m_NetworkingManager.m_speedUpEvent.AddListener(SynOtherSpeed);
                m_NetworkingManager.m_stopMoveEvent.AddListener(SynOtherStopMove);
                m_NetworkingManager.m_disconnectedEvent.AddListener(SynDisconnected);
            }

			m_OtherRoles = new OtherThirdPersonInput[m_RoleCount];
		}

		void Update ()
		{
			if (m_isInited && m_isCooling) {
				m_Timer += Time.deltaTime;

				/*m_CoolingImage.fillAmount = (m_CoolTime - m_Timer) / m_CoolTime;
				if (m_Timer > m_CoolTime) {
					setShootButtonCooling (false);
					m_Timer = 0;
				}*/
			}
		}
			

		private IEnumerator Relive() {
	
			yield return m_ReliveWait; 

            resetRole(true, m_SelfRole.m_PlayerNumber);
            SynAllSynDataOfSelfRole();

            //m_followControl.SetColorCorrectionCurvesSaturation(1);
            m_RelifeEvent.Invoke();
		}

		public void setShootButtonCooling(bool isCooling) 
		{
			m_isCooling = isCooling;
			m_SelfMessage.text = isCooling ? "<color=#2D44B0FF>正在装配子弹....</color>" : "子弹装配完成";

            //m_SelfRole.m_ShootButton.enabled = !isCooling;
		}

        public void createSelfRole (byte index)
		{
			m_SelfRole = new SelfThirdPersonInput();
            float x = m_positionArray[index % 4, 0];
            float z = m_positionArray[index % 4, 1];

			Vector3 initPos = new Vector3 (x, 0f, z);
            Color initColor = new Color();

            initPos = SpawnPoint[0].transform.position;


            m_SelfRole.m_Instance = Instantiate (m_Prefab, initPos, m_Prefab.transform.rotation) as GameObject;
            m_ThirdPersonCamera.Target = m_SelfRole.m_Instance.GetComponent<CharacterMotor>();
            StringBuilder sb = new StringBuilder();
            sb.Append("坦克");
            sb.Append(index);
            sb.Append("号");

            if (m_SelfRole.initRole (index, initColor, sb.ToString(), initPos)) {
                //m_followControl.m_followTarget = m_SelfRole.m_Instance.transform;
                if (m_SelfRole.m_moveEvent == null)
                {
                    m_SelfRole.m_moveEvent = new UnityEvent();
                }
				m_SelfRole.m_moveEvent.AddListener (SynSelfRoleMove);
				/*m_SelfRole.m_Shooting.m_ShootEvent.AddListener (SynSelfShoot);
				m_SelfRole.m_Health.m_HealthEvent.AddListener (SynSelfHealth);
				m_SelfRole.m_Shooting.m_CoolingEvent.AddListener (setShootButtonCooling);
				m_SelfRole.m_Health.m_DeathEvent.AddListener (SynSelfDeath);
                m_SelfRole.m_Movement.m_speedEvent.AddListener(SynSelfSpeed);
                m_SelfRole.m_Movement.m_stopMoveEvent.AddListener(SynSelfStopMove);*/
                
				m_isInited = true;
				//SynAllSynDataOfSelfRole ();
			}
		}

		public void SynAllSynDataOfSelfRole () {
			Hashtable table = new Hashtable ();
			table.Add ("name", SYN_SELF.ALL_DATA);
			table.Add ("pos", m_SelfRole.m_Instance.transform.position);

            m_NetworkingManager.doSynLocalData (table);
		}
				
		public void createOtherRoles(ROLE_DATA RoleData,bool isUpdate) {
            // 如果isUpdate == true , 就更新本地其它坦克数据, 否则创建新坦克  
            OtherThirdPersonInput Role = m_OtherRoles[RoleData.index];
            if (Role != null) {
				if (Role.m_Instance != null)
				{
                    float x = RoleData.position.x;
                    float z = RoleData.position.y;
					Role.m_Instance.transform.position = new Vector3(x, 0, z);
				}
				return;
			}

            OtherThirdPersonInput otherRole = new OtherThirdPersonInput();
			otherRole.m_Instance = Instantiate (m_OtherPrefab, new Vector3(RoleData.position.x, 0f, RoleData.position.y), m_OtherPrefab.transform.rotation) as GameObject;

			StringBuilder sb = new StringBuilder();
			sb.Append("坦克");
			sb.Append(RoleData.index);
			sb.Append("号");

            if(otherRole.initRole (RoleData.index, RoleData.color, sb.ToString(), new Vector3(RoleData.position.x, 0f, RoleData.position.y), RoleData.health) ){
				m_OtherRoles [RoleData.index] = otherRole;
			}
		}

        private void resetRole (bool isSelf, byte index, bool isUpdate = false) {
            ThirdPersonInput Role;
            if (isSelf) {
                Role = m_SelfRole;
            }else{
                Role = m_OtherRoles[index];
            }

			if (Role.m_Instance != null) {
				float x = m_positionArray[index % 4, 0];
				float z = m_positionArray[index % 4, 1];
                Role.m_Instance.transform.position = new Vector3 (x, 0, z);
			}
		}
			
		/*
		 * 同步位置
		 */
		public void SynSelfRoleMove() {
            Vector3 pos = m_SelfRole.m_Instance.transform.position;

			Hashtable table = new Hashtable ();
			table.Add ("name", SYN_SELF.POSTION);
            table.Add ("pos", pos);
			m_NetworkingManager.doSynLocalData (table);
		}


        public void SynOtherRoleMove(byte index, Vector3 pos){

			OtherThirdPersonInput Role = m_OtherRoles [index];

			if (Role != null) {
                Role.OnOtherMove(pos);
			}
		}

		/*
		 * 同步普通射击
		 */
		public void SynSelfShoot(){

			Hashtable table = new Hashtable ();
			table.Add ("name", SYN_SELF.SHOOT);
			table.Add ("isshoot", 1);
			m_NetworkingManager.doSynLocalData (table);
		}

        public void SynOtherShoot(byte index, float param1, float param2){
            OtherThirdPersonInput Role = m_OtherRoles [index];
            
		}

		/*
		 * 同步血量
		 */
		public void SynSelfHealth(float health) {
			Hashtable table = new Hashtable ();
			table.Add ("name", SYN_SELF.HEALTH);
			table.Add ("health", health);
			m_NetworkingManager.doSynLocalData (table);
		}

        public void SynOtherHealth(byte index, float health, float param) {

		}

		/*
		 * 同步死亡讯息  index是杀死你的人
		*/
        public void SynSelfDeath(byte index) {
            /*m_SelfRole.DisbleControl();

			StringBuilder sBuilder = new StringBuilder();
			sBuilder.Append("你被");
			sBuilder.Append(index);
			sBuilder.Append("号坦克干掉了!!!");
            m_OverEvent.Invoke(sBuilder.ToString());

            m_followControl.SetColorCorrectionCurvesSaturation(0);

			Hashtable table = new Hashtable ();
			table.Add ("name", SYN_SELF.DEATH);
            table.Add ("index", (int)index);
			m_NetworkingManager.doSynLocalData (table);*/
		}

        public void SynOtherDeath(byte index, byte killerIndex) {
            /*StringBuilder sb = new StringBuilder();
            sb.Append("<color=#2D44B0FF>坦克");
            sb.Append(killerIndex);
            sb.Append("号</color>干掉了<color=#FF00B0FF>坦克");
            sb.Append(index);
            sb.Append("号</color>");
            _worldMessageControl.setContent(sb.ToString());

			OtherRole Role = m_OtherRoles [index];
			if (Role.m_Health != null) 
			{
                Role.m_Health.TakeDamage(index, 0);
			}*/
		}

        public void SynSelfSpeed (float speed) {
            Hashtable table = new Hashtable();
            table.Add("name", SYN_SELF.SPEED_UP);
            table.Add("speed", speed);
            m_NetworkingManager.doSynLocalData(table);
        }

        public void SynOtherSpeed (byte index, float speed) {
            /*OtherRole Role = m_OtherRoles[index];

            if (Role.m_Movement != null) 
            {
                Role.m_Movement.setSpeed(speed);
            }*/
        }

        public void SynSelfStopMove () {
            Hashtable table = new Hashtable();
            table.Add("name", SYN_SELF.STOP_MOVE);
            table.Add("stopmove", 1);
            m_NetworkingManager.doSynLocalData(table);
        }

        public void SynOtherStopMove (byte index) {
            /*OtherRole Role = m_OtherRoles[index];

            if (Role.m_Movement != null)
            {
                Role.m_Movement.OnMoveEnd();
            }*/
        }

		public void SynSelfLockedTarget(Vector3 pos) {
			Hashtable table = new Hashtable ();
			table.Add ("name", SYN_SELF.LOCKED_TARGET);
			table.Add ("pos", pos);
			m_NetworkingManager.doSynLocalData (table);
		}

        public void SynOtherLockedTarget(byte index, float x, float z) {
			/*OtherRole Role = m_OtherRoles [index];

			if (Role.m_Shooting != null) {
				Vector3 new_pos = new Vector3 (x, 0, z);
				Rigidbody new_rigi = new Rigidbody ();
				new_rigi.position = new_pos;
			}*/
		}

        public void SynDisconnected (byte index) {
            /*Debug.Log("断开连接" + index);
            if (index == m_SelfRole.m_PlayerNumber) {
                //m_OverEvent.Invoke("不好意思,你掉线了,请检查网络!");
                //m_followControl.SetColorCorrectionCurvesSaturation(0);
				m_SelfRole.DisbleControl();
                Hashtable table = new Hashtable();
                table.Add("name", SYN_SELF.DISCONNECTED);
                table.Add("disconnected", 1);
                m_NetworkingManager.doSynLocalData(table);
            } else {
                OtherRole Role = m_OtherRoles[index];

                if (Role != null && Role.m_Instance != null) {
                    Destroy(Role.m_Instance.gameObject);
                }
            }*/
        }
			
	}
}

